// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

const WIDTH = 143;

@ccclass
export default class ClickBox extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property(cc.Node)
    touchNode: cc.Node = null;

    @property([cc.Component.EventHandler])
    clickEvents: cc.Component.EventHandler[] = [];

    startIdx = -1;
    customData = '';

    protected onEnable() {
        this.touchNode.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.touchNode.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    protected onDisable() {
        this.touchNode.off(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.touchNode.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    onTouchStart(e: cc.Event.EventTouch) {
        this.startIdx = this.touchToIdx(e.getLocation());
    }
    onTouchEnd(e: cc.Event.EventTouch) {
        let endIdx = this.touchToIdx(e.getLocation());
        if (endIdx >= 0 && endIdx == this.startIdx) {
            cc.Component.EventHandler.emitEvents(this.clickEvents, endIdx, this.customData);
        }
        this.startIdx = -1;
    }

    touchToIdx(e: cc.Vec2, offset: cc.Vec2 = null): number {
        if (offset) {
            e = e.add(offset);
        }
        let loc = this.touchNode.convertToNodeSpaceAR(e);
        loc.addSelf(cc.v2(WIDTH * 2.5, WIDTH * -2.5));
        loc.mulSelf(1 / WIDTH);
        let x = Math.floor(loc.x);
        let y = Math.floor(-loc.y);
        if (x < 0 || x > 4 || y < 0 || y > 4) {
            return -1;
        }
        return x + y * 5;
    }

    showPanel(text: string) {
        this.label.string = text;
        this.node.active = true;
    }

    show1() {
        this.showPanel('点击任意数字合成该数字');
        this.customData = '1';
    }
    show2() {
        this.showPanel('点击棋盘消除所有连接');
        this.customData = '2';
    }

    close() {
        this.node.active = false;
    }
}
